package database;

import java.io.File;
import java.sql.ResultSet;
import java.sql.Statement;

import main.Main;
import database.dbObjects.*;
import database.dbObjects.IDBObject.DBObject;
import database.dbRelations.*;

public class Database extends DBObject implements IDBExam, IDBFile, IDBLesson, IDBProject, 
		IDBStudent, IDBCourse, IDBTask, IDBTeacher, IDBContact, IDBEvent, IDBRelCourseFile, 
		IDBRelCourseTask, IDBRelCourseTeacher, IDBRelProjectStudent, IDBRelTaskEvent, 
		IDBRelTaskFile {
	
	public final DBCourse course = new DBCourse();
	public final DBFile file = new DBFile();
	public final DBEvent event = new DBEvent();
	public final DBLesson lesson = new DBLesson();
	public final DBContact contact = new DBContact();
	public final DBStudent stud = new DBStudent();
	public final DBTeacher teach = new DBTeacher();
	public final DBTask task = new DBTask();
	public final DBProject proj = new DBProject();
	public final DBExam exam = new DBExam();
	
	public final DBRelCourseFile rCF = new DBRelCourseFile();
	public final DBRelCourseTask rCTask = new DBRelCourseTask();
	public final DBRelCourseTeacher rCTeach = new DBRelCourseTeacher();
	public final DBRelProjectStudent rPS = new DBRelProjectStudent();
	public final DBRelTaskEvent rTE = new DBRelTaskEvent();
	public final DBRelTaskFile rTF = new DBRelTaskFile();
	
	
	public Database(String dbName) {
		this.dbName = dbName;
	}
	
	public final String getDBName() {
		return this.dbName;
	}
	
	public final void setDBName(String dbName) {
		this.dbName = dbName;
	}
	
	public final ResultSet getSomething(String sql) throws Exception {
		
		Statement stat = Main.connection.createStatement();
		return stat.executeQuery(sql);
	}
	
	public final boolean createDBFile(boolean override) throws Exception {
		
/** TODO zie fout in userdb!! -> createTables */
		
		String fileName = dbName;
		File f = new File(fileName);
		
		if ( (!f.exists()) && (f.createNewFile()) ) {
            createTables();
			return true;
		} else if (override) {
			if (!f.delete()) {
				throw (new Exception("Database file could not be deleted!"));
			}
			if (!f.createNewFile()) {
				throw (new Exception("Database file could not be created!"));
			}
			createTables();
			return true;
		}
		
		return false;
	}
	
	private final void createTables() throws Exception {
		
		course.init();
		file.init();
		event.init();
		lesson.init();
		contact.init();
		stud.init();
		teach.init();
		task.init();
		proj.init();
		exam.init();
		
		rCF.init();
		rCTask.init();
		rCTeach.init();
		rPS.init();
		rTE.init();
		rTF.init();
	}
	
	
	private String dbName;
	
}
